package com.matriq.cloudmanager;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import com.matriq.cloudmanager.R;
import com.matriq.cloudmanager.dialog.DownloadDialog;
import com.matriq.cloudmanager.dialog.UpdateNoticeDialog;
import com.matriq.cloudmanager.fragment.ContactFragment;
import com.matriq.cloudmanager.fragment.CourseCenterFragment;
import com.matriq.cloudmanager.fragment.HomeFragment;
import com.matriq.cloudmanager.fragment.MessageFragment;
import com.matriq.cloudmanager.fragment.PersonalFragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v4.app.Fragment;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import net.lgpage.activity.BaseFragmentActivity;
import net.lgpage.dialog.DialogListener;
import net.lgpage.service.APKUpdateService;
import net.lgpage.util.MyFragmentPagerAdapter;

public class MainActivity extends BaseFragmentActivity {

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ac_main);
		setViews();
		setEvents();
		loadData();
		startUpdateValidate();
		registerNetworkReceiver();
	}

	private long exitTime = 0;

	@Override
	public void onBackPressed() {
		if (System.currentTimeMillis() - exitTime > 2000) {
			Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
			exitTime = System.currentTimeMillis();
		} else {
			finish();
			System.exit(0);
			android.os.Process.killProcess(android.os.Process.myPid());
		}
	}

	private void toSetNetWork() {
		Intent intent = new Intent(Settings.ACTION_SETTINGS);
		startActivity(intent);
	}

	private NetWorkReceiver networkBroadcast;

	private void registerNetworkReceiver() {
		IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
		networkBroadcast = new NetWorkReceiver();
		this.registerReceiver(networkBroadcast, filter);
	}

	private void unRegisterNetworkReceiver() {
		if (networkBroadcast != null) {
			this.unregisterReceiver(networkBroadcast);
		}
	}

	public void unRegisterReceiver() {
		if (receiver != null) {
			unregisterReceiver(receiver);
		}
		unRegisterNetworkReceiver();
		/*
		 * if (minaReceiver != null) { unregisterReceiver(minaReceiver); }
		 */
	}

	/**
	 * 广播接收器
	 *
	 * @author len
	 *
	 */
	public class NetWorkReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			NetworkInfo.State wifiState = null;
			NetworkInfo.State mobileState = null;
			ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
			wifiState = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();
			mobileState = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState();
			if (wifiState != null && mobileState != null && NetworkInfo.State.CONNECTED != wifiState
					&& NetworkInfo.State.CONNECTED == mobileState) {
				// 手机网络连接成功
				showNetWorkView(false);
			} else if (wifiState != null && mobileState != null && NetworkInfo.State.CONNECTED != wifiState
					&& NetworkInfo.State.CONNECTED != mobileState) {
				// 手机没有任何的网络
				showNetWorkView(true);
			} else if (wifiState != null && NetworkInfo.State.CONNECTED == wifiState) {
				// 无线网络连接成功
				showNetWorkView(false);
			} else {
				showNetWorkView(true);
			}
		}
	}

	APKUpdateReceiver receiver;

	private void showNetWorkView(boolean open) {
		if (open) {
			ll_nonet.setVisibility(View.VISIBLE);
		} else {
			ll_nonet.setVisibility(View.GONE);
		}
	}

	/**
	 * 广播接收器
	 * 
	 * @author len
	 */
	public class APKUpdateReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			String url = intent.getStringExtra("url");
			String must = intent.getStringExtra("must");
			String content = intent.getStringExtra("content");
			showNoticeDialog(content,url);
		}

	}

	UpdateNoticeDialog noticeDialog;

	private void showNoticeDialog(String content,final String apkUrl) {
		if (noticeDialog == null) {
			noticeDialog = new UpdateNoticeDialog(this);
			noticeDialog.setData(content);
			noticeDialog.setListener(new DialogListener() {

				@Override
				public void onDialogExecute(Object... obj) {
					showDownloadDialog(apkUrl);
				}
			});
		}
		noticeDialog.show();
	}

	private void showDownloadDialog(String apkUrl) {
		DownloadDialog dd = new DownloadDialog(getActivity());
		dd.setData("更新包下载中", apkUrl, "dowish.apk");
		dd.setListener(new DialogListener() {
			
			@Override
			public void onDialogExecute(Object... os) {
				File file = (File) os[0];
				installApk(file);
			}
		});
		dd.show();
		dd.download();
	}

	/**
	 * 安装apk
	 * 
	 * @param url
	 */
	private void installApk(File apkfile) {
		if (!apkfile.exists()) {
			return;
		}
		Intent i = new Intent(Intent.ACTION_VIEW);
		i.setDataAndType(Uri.parse("file://" + apkfile.toString()), "application/vnd.android.package-archive");
		startActivity(i);
	}

	public void startUpdateValidate() {
		// 绑定Service
		Intent intent = new Intent(this, APKUpdateService.class);
		startService(intent);
		registerReceiver();
	}

	public void registerReceiver() {
		// 动态注册广播接收器
		receiver = new APKUpdateReceiver();
		IntentFilter intentFilter = new IntentFilter();
		intentFilter.addAction("com.lg.broadcast.apkupdate");
		registerReceiver(receiver, intentFilter);
	}

	TextView tv_num;
	LinearLayout root;
	TextView tv_tab[] = new TextView[4];
	ImageView iv_tab[] = new ImageView[4];
	RelativeLayout rl_tab[] = new RelativeLayout[4];
	LinearLayout ll_nonet;
	android.support.v4.view.ViewPager vp;

	List<Fragment> fmlist;

	private void setViews() {
		tv_num = (TextView) this.findViewById(R.id.tv_num);
		root = (LinearLayout) this.findViewById(R.id.root);
		tv_tab[0] = (TextView) this.findViewById(R.id.tv_tab0);
		tv_tab[1] = (TextView) this.findViewById(R.id.tv_tab1);
		tv_tab[2] = (TextView) this.findViewById(R.id.tv_tab2);
		tv_tab[3] = (TextView) this.findViewById(R.id.tv_tab3);
		iv_tab[0] = (ImageView) this.findViewById(R.id.iv_tab0);
		iv_tab[1] = (ImageView) this.findViewById(R.id.iv_tab1);
		iv_tab[2] = (ImageView) this.findViewById(R.id.iv_tab2);
		iv_tab[3] = (ImageView) this.findViewById(R.id.iv_tab3);
		rl_tab[0] = (RelativeLayout) this.findViewById(R.id.rl_tab0);
		rl_tab[1] = (RelativeLayout) this.findViewById(R.id.rl_tab1);
		rl_tab[2] = (RelativeLayout) this.findViewById(R.id.rl_tab2);
		rl_tab[3] = (RelativeLayout) this.findViewById(R.id.rl_tab3);
		ll_nonet = (LinearLayout) this.findViewById(R.id.ll_nonet);
		vp = (android.support.v4.view.ViewPager) this.findViewById(R.id.vp);
		fmlist = new ArrayList<>();
		fmlist.add(new HomeFragment());
		//fmlist.add(new CourseCenterFragment());
		fmlist.add(new MessageFragment());
		fmlist.add(new ContactFragment());
		fmlist.add(new PersonalFragment());
		pa = new MyFragmentPagerAdapter(getSupportFragmentManager(), fmlist);
		vp.setAdapter(pa);
	}

	private void setEvents() {
		ll_nonet.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				toSetNetWork();
			}
		});
		vp.setOnPageChangeListener(new OnPageChangeListener() {

			@Override
			public void onPageSelected(int position) {
				changeTab(position);
			}

			@Override
			public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

			}

			@Override
			public void onPageScrollStateChanged(int state) {

			}
		});
		for (int i = 0; i < rl_tab.length; i++) {
			rl_tab[i].setTag(i);
			rl_tab[i].setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					changeTab((int) v.getTag());
				}
			});
		}
	}

	private void changeTab(int index) {
		for (int i = 0; i < tv_tab.length; i++) {
			tv_tab[i].setTextColor(0xffbdbdbd);
		}
		iv_tab[0].setImageResource(R.drawable.tab_btn_home_nor);
		iv_tab[1].setImageResource(R.drawable.tab_btn_news_nor);
		iv_tab[2].setImageResource(R.drawable.tab_btn_contacts_nor);
		iv_tab[3].setImageResource(R.drawable.tab_btn_personal_nor);
		switch (index) {
		case 0:
			iv_tab[index].setImageResource(R.drawable.tab_btn_home_pressed);
			break;
		case 1:
			iv_tab[index].setImageResource(R.drawable.tab_btn_news_pressed);
			break;
		case 2:
			iv_tab[index].setImageResource(R.drawable.tab_btn_contacts_pressed);
			break;
		case 3:
			iv_tab[index].setImageResource(R.drawable.tab_btn_personal_pressed);
			break;
		default:
			break;
		}
		tv_tab[index].setTextColor(0xffd34a40);
		vp.setCurrentItem(index);
	}

	PagerAdapter pa;

	private void loadData() {
		changeTab(0);
	}

	@Override
	public void onDestroy() {
		unRegisterReceiver();
		super.onDestroy();
	}

}